<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');


class Security extends CI_Controller {
    var $datah, $ids ;
    
    public function __construct()
	{
                // parent::Controller();
		parent::__construct();
                $this->load->model('security_model');
                $this->load->model('users_model');
                $this->load->model('menu_model');
                $this->load->helper('url');
                $this->datah['baseurl'] = base_url();
                session_start();
                $role = 'public';   // predefine the var 
                if (isset($_SESSION)) {
                    if ( isset($_SESSION['logged_in'])) {
                        $role = $_SESSION['role']; } else { $role = 'public'; } } 
            
                $this->datah['role'] = $role;   
                $this->datah['menu'] = $this->menu_model->getmenu( $role ,'users' );
                // LOAD LIBRARIES
                $this->load->library(array('encrypt', 'form_validation' ));
                // LOAD HELPERS
                $this->load->helper(array('form'));
	}
        
   public function verifycrud ($page) {
       // funtion to determin the users rights for a page in terms of CRUD 
       
   }   
   
   public function prelogin () {
       // funtion log a user in and get the available area's that they are connected to
            $page = "Login";
            $un = "";
            $pw = "";
            $this->datah['title'] = ucfirst($page);
            $this->datah['showmenu'] = FALSE;
            $data['title'] = 'Credentials Check';
	
            $this->form_validation->set_rules('user_name', 'Username', 'required');
            $this->form_validation->set_rules('passwd', 'Password', 'required | min_length[6]');
            $this->form_validation->set_error_delimiters('<em>','</em>');
            
            $this->load->view('templates/header', $this->datah);
            $this->load->view('security/login');
            $this->load->view('templates/footer');
            
            if( $this->input->post('login') )  // is the login button set
            {
                if( $this->form_validation->run() )   // run the validation
                {
                    // if the validation is sucessfull
                    $user_name = $this->input->post('user_name');
                    $user_pass = $this->input->post('passwd'); //encrypt->encode($this->input->post('passwd'));  
                    //echo '<script language="javascript">confirm(" Encrypt : '. $this->input->post('passwd'). ' : '.$user_pass.'"); </script>';
                  //  var_dump($user_pass);
                  //  var_dump($this->encrypt->decode($user_pass));
                    // continue processing form (validate password)
                    $login = array('username' => $user_name, 'passwd' => $user_pass) ;
                    $result = $this->security_model->CheckCred($login);
                    // if loggedin = true then create the session
                    
                    if ( isset($result['Name'] ) ) {
                        $_SESSION['Name'] = $result['Name'];
                        $_SESSION['PublicName'] = $result['PublicName'];
                        $_SESSION['email'] = $result['username'];
                        $_SESSION['mobile'] = $result['mobile'];
                        $_SESSION['IP'] = $this->GetIp();
                        $_SESSION['message'] = '';
                        $_SESSION['userdata'] = [];
                        if ($result['active'] == TRUE) {
                            $_SESSION['role'] =  $result['role']; 
                            $_SESSION['level'] = $result['level'];
                            $_SESSION['uid'] = $result['_id'];
                            $_SESSION['area'] = $result['areas'];
                            $_SESSION['group'] = $result['grp'];
                            $_SESSION['curarea'] = '';
                            $_SESSION['curareaname'] = '';
                            $_SESSION['curgrp'] = array('gid' => '', 'GroupName' => '');
                        } else {
                            $_SESSION['role'] = 'Public';
                            $_SESSION['level'] = 9;
                            $_SESSION['uid'] = $result['_id'];
                            $_SESSION['area'] = array();
                            $_SESSION['group'] = array();
                            $_SESSION['curarea'] = '';
                            $_SESSION['curareaname'] = '';
                            $_SESSION['curgrp'] = array('gid' => '', 'GroupName' => '');
                        }
                            $_SESSION['logged_in'] = TRUE;
                            //$this->setarea();
                            // TODO : if changepass is set force the user to change their password 
                            //$_SESSION['message'] = count($_SESSION['area']);
                            if (count($_SESSION['area']) > 1) {
                               redirect('index.php/setarea', $result);
                            } else { 
                                $_SESSION['curarea'] = $result['areas'][0]['area'];
                                $_SESSION['curareaname'] = $result['areas'][0]['areaname'];
                             //   $_SESSION['curarea'] = $this->setmultiarray($result['areas']); 
                              redirect(base_url());
                            }
                    } else {
                        //$this->session->set_flashdata('message', 'Username & Password do not match 1.');
                        $this->clearsession();
                        redirect(base_url());
                        // redirect('index.php/setarea');
                    }
                } else {
                        // form validation failed
                        //$this->session->set_flashdata('message', 'Username & Password do not match 2.');
                        redirect('security/prelogin');
                        
                        }
                }
   }  
   
   public function setarea ( $rdata ) {
       $page = "Select Default Area";
       $this->datah['title'] = ucfirst($page);
       $this->datah['showmenu'] = FALSE;
       // $areasraw = $this->users_model->getareas();
       $user['areas'] = $rdata['areas'];
       $this->load->view('templates/header', $this->datah);
       // Load the form
       $this->load->view('security/SelectArea', $user);
       $this->load->view('templates/footer');
       
       if( $this->input->post('area') )  // is the area button set
        {   
         $_SESSION['curarea'] = array('aid' => $this->input->post('areaset'), 'AreaName' => '');  
         $areadata = $this->users_model->getareabyid($this->input->post('areaset'));
         //var_dump($areadata);
         $_SESSION['curarea'] = array('aid' => $this->input->post('areaset'), 'AreaName' => $areadata[0]['Area']);    
         redirect(base_url());
        }
 }

   public function logout() {
       // funtion to logout the user
       $page = "Logout";
       $bu = base_url();
       session_unset();
       session_destroy();
       session_start();
       $this->clearsession();
       redirect(base_url());
   }
   
   public function adduser( $userdata ) {
       // funtion to add a user
   }
   
   function clearsession(){
       $_SESSION['Name'] = '';
       $_SESSION['email'] = '';
       $_SESSION['mobile'] = '';
       $_SESSION['role'] = 'public';
       $_SESSION['level'] = 99;
       $_SESSION['uid'] = '';
       $_SESSION['area'] = array();
       $_SESSION['group'] = array();
       $_SESSION['curarea'] = '';
       $_SESSION['curareaname'] = '';
       $_SESSION['curgrp'] = array('gid' => '', 'GroupName' => '');
       $_SESSION['logged_in'] = FALSE;
       $_SESSION['IP'] = $this->GetIp();
       $_SESSION['userdata'] = [];
       $_SESSION['message'] = '';
   }
   
   function setmultiarray($data) {
       $result = [];
       foreach ($data as $key => $value ) {
           $t = array($key => $value);
           $result = array_merge($result, $t);
       }
       
       return $result;
   }
   
   function GetIp() {
       if (!empty($_SERVER["HTTP_CLIENT_IP"]))
        {
            //check for ip from share internet
            $ip = $_SERVER["HTTP_CLIENT_IP"];
        }
            elseif (!empty($_SERVER["HTTP_X_FORWARDED_FOR"]))
            {
                // Check for the Proxy User
                $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
            }
            else
                {
                    $ip = $_SERVER["REMOTE_ADDR"];
                }
            // This will print user's real IP Address
            // does't matter if user using proxy or not.
            return $ip;
   }
   
}

?>
